package com.lloydfinch.mvvm;

import android.annotation.SuppressLint;
import android.arch.lifecycle.LifecycleOwner;

import com.lloydfinch.bblayer.UserBean;
import com.lloydfinch.mvvm.databinding.ActivityMainBinding;

public class MainUIController {
    // 数据
    private MainViewModel mainViewModel;
    // UI
    private ActivityMainBinding rootView;

    public MainUIController(ActivityMainBinding rootView, MainViewModel mainViewModel) {
        this.mainViewModel = mainViewModel;
        this.rootView = rootView;
        init();
    }

    public void init() {
        rootView.btnTest.setOnClickListener(v -> {
            mainViewModel.addUser(new UserBean());
        });
    }

    @SuppressLint("SetTextI18n")
    public void attach(LifecycleOwner lifecycleOwner) {
        mainViewModel.getUserBeans().observe(lifecycleOwner, userBeans -> {
            rootView.tvTest.setText("size: " + userBeans.size());
        });
    }

    /**
     * 这里不用手动调用，除非特别情况需要
     *
     * @param lifecycleOwner
     */
    public void detach(LifecycleOwner lifecycleOwner) {
        mainViewModel.getUserBeans().removeObservers(lifecycleOwner);
    }
}
